package com.hua.utility.encrypt;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class EncryptionMAC {

	/**
	 * MAC算法可选以下多种算法(非可逆加密)
	 * 
	 * <pre>
	 * HmacMD5 
	 * HmacSHA1 
	 * HmacSHA256 
	 * HmacSHA384 
	 * HmacSHA512
	 * </pre>
	 */
	public static final String KEY_MD5 = "HmacMD5";
	public static final String KEY_SHA1 = "HmacSHA1";
	public static final String KEY_SHA256 = "HmacSHA256";
	public static final String KEY_SHA384 = "HmacSHA384";
	public static final String KEY_SHA512 = "HmacSHA512";

	private String encryptType = "HmacMD5";

	/**
	 * 初始化HMAC密钥
	 * 
	 * 生成encryptHMAC 的 key
	 * 
	 * @return
	 * @throws NoSuchAlgorithmException
	 * 
	 */
	public String initMacKey() throws NoSuchAlgorithmException {
		KeyGenerator keyGenerator = KeyGenerator.getInstance(encryptType);
		SecretKey secretKey = keyGenerator.generateKey();
		return (new BASE64Encoder()).encodeBuffer(secretKey.getEncoded());
	}

	/**
	 * HMAC加密(非可逆加密)
	 * 
	 * 基于密钥的Hash算法的认证协议。
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeyException
	 * 
	 */
	public byte[] encryptHMAC(byte[] data, String key)
			throws IOException, NoSuchAlgorithmException, InvalidKeyException {
		SecretKey secretKey = new SecretKeySpec((new BASE64Decoder()).decodeBuffer(key), encryptType);
		Mac mac = Mac.getInstance(secretKey.getAlgorithm());
		mac.init(secretKey);
		return mac.doFinal(data);

	}

	public String getEncrptyType() {
		return encryptType;
	}

	public void setEncrptyType(String encryptType) {
		if (KEY_MD5.equalsIgnoreCase(encryptType)) {
			this.encryptType = KEY_MD5;
		} else if (KEY_SHA1.equalsIgnoreCase(encryptType)) {
			this.encryptType = KEY_SHA1;
		} else if (KEY_SHA256.equalsIgnoreCase(encryptType)) {
			this.encryptType = KEY_SHA256;
		} else if (KEY_SHA384.equalsIgnoreCase(encryptType)) {
			this.encryptType = KEY_SHA384;
		} else if (KEY_SHA512.equalsIgnoreCase(encryptType)) {
			this.encryptType = KEY_SHA512;
		} else {
			this.encryptType = KEY_MD5;
		}
	}

}